package com.yc.navy.dayfresh.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.yc.navy.dayfresh.entity.User;
import com.yc.navy.dayfresh.mapper.UserMapper;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

/**
 * @author navy
 * @company 源辰信息
 * @date 2024/9/18
 * @email haijunzhou@hnit.edu.cn
 */

@Component
@ServerEndpoint("/talk/{id}")
public class TalkDo {
    // WebScoket容器会为每个会话会创建一个 TalkDo;
    private static Map<String, Session> sessionMap = new ConcurrentHashMap<>();

    // spring 不会注入静态属性
    static UserMapper userMapper;

    @Autowired
    public void setUserMapper(UserMapper userMapper) {
        TalkDo.userMapper = userMapper;
    }

    @OnOpen
    public void onOpen(Session session,
                       @PathParam("id") String id) throws IOException {
        sessionMap.put(id, session);
        session.getUserProperties().put("id",id);
        User user = userMapper.selectById(id);
        session.getUserProperties().put("user",user);
        System.out.println(user.getName() + " 上线啦!");
        send(user, "txt:上线了!");
    }

    @OnClose
    public void aaaa(Session session) throws IOException {
        User user = (User) session.getUserProperties().get("user");
        System.out.println(user.getName() + " 说: " + " 下线啦!");
        Object id = session.getUserProperties().get("id");
        sessionMap.remove(id);
        send(user,"txt:下线啦!");
    }

    @OnMessage
    public void bbbb(Session session, String msg) throws IOException {
        User user = (User) session.getUserProperties().get("user");
        System.out.println(user.getName() + " 说: " + msg);
        send(user,msg);
    }

    public void send(User user, String content) throws IOException {
        // 集合流式编程
        List<User> onlines = sessionMap
                .values()  // 获取会话集合
                .stream() // 转为流
                .map(session->{
                    return (User)session.getUserProperties().get("user");
                })        // 将会话集合转为User集合
                .collect(Collectors.toList()); // 收集list集合
        Msg msg = new Msg(user,content, onlines);
        String json = new ObjectMapper().writeValueAsString(msg);
        for (Map.Entry<String, Session> entry : sessionMap.entrySet()) {
            String i = entry.getKey();
            Session s = entry.getValue();
            s.getBasicRemote().sendText(json);
        }
    }

}

@Data
@AllArgsConstructor
@NoArgsConstructor
class Msg{
    User sender;
    String content;
    List<User> onlines;
}
